const userListEle = document.querySelector('#user-list') //tbody
const usersBaseUrl = "http://47.105.173.95:3000/api/users"
let gCurrentPage = 1;
let pageCount = 1
let gPageSize = 20
let gCurrentUser;

/*-----------------------网络请求相关------------------------- */

//根据传入的参数获取用户数据
function getUsers(params, success, error) {
    ajax(usersBaseUrl, {
        data: params,
        success: function (res) {
            if(typeof success == 'function'){
                success(res.results)
            }   
        },
        error: function (res, statusText, xhr) {
            myalert.toastError('当前用户不存在')
            if(typeof error == 'function'){
                error(res, statusText, xhr)
            }
            
        }
    })
}
/*-----------------设置用户列表相关-------------------- */
//初始化用户列表数据
function initUsers(page = 1, pageSize = 20) {
    console.log(page)
    console.log(gCurrentUser)
    getUsers({ _page: page, _limit: pageSize }, function (results) {
        renderUserList(results.data)
        pageCount = results.page_count
        console.log(page)
        console.log(results)
        gCurrentPage = page
        renderPagination(pageCount)
        pageActive(page)

    })
}
initUsers()
//把用户数据渲染到表格
function renderUserList(users) {
    const html = users.map(user => {
        return `
                <tr>
                    <th>${user.id}</th>
                    <th>${user.username}</th>
                    <th>${user.gender == 0 ? '男' : '女'}</th>
                    <th>${user.telephone}</th>
                    <th>${user.email}</th>
                    <th>
                        <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal-detail" data-id=${user.id} data-type="detail">详细</button>
                        <button type="button" class="btn btn-danger btn-sm" data-id=${user.id} data-type="delete">删除</button>
                    </th>
                </tr>`
    }).join('')
    userListEle.innerHTML = html
};

//给用户列表操作栏的按钮绑定事件
(function bindUserListButton() {
    userListEle.addEventListener('click', function (e) {
        const clickElement = e.target
        if (clickElement.tagName == 'BUTTON') {
            const id = clickElement.dataset.id //获取点击的详细按钮对应的id
            if (clickElement.dataset.type == 'detail') {
                //点击的是详细按钮
                setModalFormState('view')
                getUsers({ id: id }, function (results) {
                    setFormValue(detailFormOption, results.data[0])
                    gCurrentUser = results.data[0]
                })
            } else if (clickElement.dataset.type == 'delete') {
                //删除操作
                swal("你确定删除这条用户信息吗?", {
                    dangerMode: true,
                    buttons: {
                        cancel: {
                            text: "取消",
                            visible: true,
                        },
                        confirm: {
                            text: "删除",
                            closeModal: false
                        }
                    }
                }).then((value) => {
                    if (value) {
                        const url = usersBaseUrl + `/${id}`
                        ajax(url, {
                            method: 'delete',
                            error: function () {
                                myalert.toastSuccess('删除成功')
                                initUsers(gCurrentPage, gPageSize)
                            }
                        })
                    }
                })
                // const url = usersBaseUrl + `/${id}`
                // ajax(url,{
                //     method:'delete',
                //     error:function(){
                //         myAlert({content:'删除成功'})
                //         initUsers(gCurrentPage,gPageSize)
                //     }
                // })
            }
        }
    });
})()


/*------------------用户详细表单相关---------------------- */
//表单配置文件
const detailFormOption = {
    id: {
        selector: '#u-id',//选择器
        dataKey: "id",//对应的返回数据中的键
    },
    username: {//字段名称
        selector: '#username',//选择器
        dataKey: "username",//对应的返回数据中的键
        element: null //输入框元素，由后面的initDetailFormElement函数获取并挂载到此处
    },
    email: {
        selector: '#email',
        dataKey: 'email'
    },
    nickname: {
        selector: "#nickname",
        dataKey: "nicheng"
    },
    telephone: {
        selector: '#telephone',
        dataKey: "telephone"
    },
    birthday: {
        selector: '#birthday',
        dataKey: "birthday"
    },
    gender: {
        selector: "[name=gender]",//checkbox和radio推荐使用name做为选择器
        dataKey: 'gender'
    },
    state: {
        selector: "#state",
        dataKey: 'state'
    },
    addr: {
        selector: "#addr",
        dataKey: 'address'
    },
    loginTime: {
        selector: "#login-time",
        dataKey: 'time'
    },
    intro: {
        selector: "#intro",
        dataKey: 'intro'
    },
    permission: {
        selector: "[name='permission']",
        dataKey: 'permission'
    }
};

//把所有字段对应的输入框找到并挂载到detailFormFieldElement里面
(initFormFieldOption)(detailFormOption)


/*-------------------------分页相关----------------------------------- */
const paginationEle = document.querySelector('.pagination');
const pageSizeEle = document.getElementById('page-size');
(function bindPagination() {
    paginationEle.onclick = function (e) {
        //阻止事件默认行为
        e.preventDefault();
        const clickElement = e.target
        const page = clickElement.dataset.page//1,2,3,next,prev     
        handleSwitchpage(page, gPageSize)
    }
    pageSizeEle.onchange = function (e) {
        console.log('pagesize改变了')
        console.log(this.value)
        const targetPageSize = this.value
        //请求网络
        handleSwitchpage(gCurrentPage, targetPageSize)
    }

})()

//负责切换到对应的页面，并把数据渲染到网页
function handleSwitchpage(page, pageSize = gPageSize) {
    let targetPage;
    if (!isNaN(page)) {
        targetPage = page
    } else if (page == 'next') {
        if (gCurrentPage >= pageCount) { return }
        targetPage = gCurrentPage + 1
    } else if (page == 'prev') {
        if (gCurrentPage <= 1) { return }
        targetPage = gCurrentPage - 1
    }
    //如果每页数量在改变，自动跳转到第一页
    if (pageSize != gPageSize) {
        targetPage = 1
    }
    //根据页面和每页的数量请求页码对应的用户数据
    getUsers({ _page: targetPage, _limit: pageSize }, function (results) {
        renderUserList(results.data)
        renderPagination(results.page_count)
        pageActive(results.page)
        gCurrentPage = parseInt(targetPage)
        pageCount = parseInt(results.page_count)
        gPageSize = parseInt(pageSize)


    })
    //把数据渲染到页面
}
//激活当且页码
function pageActive(page) {
    const pageLis = paginationEle.querySelectorAll('li')
    const nextPageEle = paginationEle.querySelector('.page-next')
    const prevPageEle = paginationEle.querySelector('.page-prev')
    // console.log(pageLis)
    pageLis.forEach(li => {
        if (li.dataset.page == page) {
            li.classList.add('active')
        } else {
            li.classList.remove('active')
        }
    })
    if (page >= pageCount) {
        nextPageEle.classList.add('disabled')
    } else if (page <= 1) {
        prevPageEle.classList.add('disabled')
    } else {
        nextPageEle.classList.remove('disabled')
        prevPageEle.classList.remove('disabled')
    }

}
//根据页面的总数动态的生成分页器
function renderPagination(pageCount, activePage = 1) {
    let lis = ''
    for (i = 1; i <= pageCount; i++) {
        lis += `<li class="${i == activePage ? 'active' : ''}" data-page=${i}><a href="#" data-page=${i}>${i}</a></li>`
    }

    const html = `
    <li class="page-prev">
        <a href="#" aria-label="Previous" data-page="prev">
            <span aria-hidden="true" data-page="prev">&laquo;</span>
        </a>
    </li>
    ${lis}
    <li class="page-next">
        <a href="#" aria-label="Next" data-page="next">
            <span aria-hidden="true" data-page="next">&raquo;</span>
        </a>
    </li>`
    paginationEle.innerHTML = html

};
/*---------------------------搜索用户-----------------------------------------*/
(function bindSearch() {
    const searchBtn = document.getElementById('search-btn')
    const userIdIpt = document.getElementById('user-id')
    searchBtn.onclick = function (e) {
        e.preventDefault()
        const userId = userIdIpt.value
        if(!userId){
            myalert.toastError('请输入用户Id')
            return 
        }
        getUsers({ id: userId }, function (results) {
            const user = results.data[0]
            //1.打开模态框
            $("#modal-detail").modal('show')
            //2.把数据设置给表单
            setFormValue(detailFormOption, user)
        })
    }
})();
/*-----------------------------添加用户-----------------------------------------*/
let gFormState = 'read';//表单的状态，read,write
(function bindAddUser() {
    const addUserBtn = document.getElementById('add-user')
    addUserBtn.onclick = function (e) {
        e.preventDefault()
        $("#modal-detail").modal('show')
        setModalFormState('add')
    }
})()

//设置表单的状态，读，写。read,write
function setFormState(state, formOption = detailFormOption) {
    let flag;
    if (state == 'read') {
        flag = true
    } else if (state == 'write') {
        flag = false
    } else {
        throw Error('表单状态不合法')
    }
    for (field in formOption) {
        const element = formOption[field].element
        if (!element) continue
        if (!Array.isArray(element)) {
            if (element.type == 'checkbox' || element.type == 'radio') {
                element.disabled = flag
            } else {
                element.readOnly = flag
            }
        } else {
            element.forEach(item => {
                item.disabled = flag
            })
        }
    }
    gFormState = state
};
(function bindnOkBtn() {
    const okBtn = document.getElementById('ok-btn')
    okBtn.onclick = function () {
        //判断模态框表单整体状态，根据状态做出对应的事情
        if (gModalFormState == 'view') {
            setModalFormState("update")
        } else if (gModalFormState == 'update') {
            //更新用户信息
            const newUserData = getFormValue()
            let userDiff = diff(newUserData, gCurrentUser)
            const url = usersBaseUrl + '/' + gCurrentUser.id
            ajax(url, {
                method: 'patch',
                data: userDiff,
                success: function (res) {
                    $('#modal-detail').modal('hide')
                    myalert.toastSuccess('修改用户成功')
                    setModalFormState("view")
                    initUsers(page = gCurrentPage, limit = gPageSize)
                }
            })
        } else if (gModalFormState == 'add') {
            //添加用户
            const user = getFormValue()
            // console.log(user)
            ajax(usersBaseUrl, {
                method: 'post',
                data: user,
                success: function (res) {
                    $('#modal-detail').modal('hide')
                    swal({
                        text:'新增用户成功！',
                        timer:1500,
                        icon:'success',
                        buttons:false
                    })
                    setModalFormState('view')
                }
            })
        } else {
            throw Error(`全局变量gModalFormState:${gModalFormState}为不合法状态`)
        }
    }
})()

function diff(obj1, obj2) {
    const res = {}
    for (let key in obj1) {
        if (obj1[key] != obj2[key]) {
            res[key] = obj1[key]
        }
    }
    return res
}
let gModalFormState = 'view'//view,update,add

function setModalFormState(state) {
    let modalOpt = {
        selector: "#modal-detail"
    }
    if (state == "view") {
        setFormState('read')
        //设置模态框
        modalOpt.title = "查看用户信息"
        modalOpt.okBtn = {
            text: "修改",
            type: 'warning'
        }
    } else if (state == 'update') {
        setFormState('write')
        modalOpt.title = "修改用户信息"
        modalOpt.okBtn = {
            text: "保存",
            type: 'danger'
        }
    } else if (state == 'add') {
        clearFormValue()
        setFormState('write')
        modalOpt.title = "新增用户信息"
        modalOpt.okBtn = {
            text: "新增",
            type: 'success'
        }
    } else {
        throw Error(`给ModalFormState设置的状态${state}不合法，只能设置view,update,add`)
    }
    setModal(modalOpt)
    //更新全局变量
    gModalFormState = state
}
/*-----------------------模态框通用---------------------------- */
//配置文件格式
// let option = {
//     selector:'模态框选择器',
//     element:'模态框元素',
//     title:'模态框标题',
//     content:'模态框内容',
//     okBtn:{
//         text:'okBtn的文字',
//         type:'按钮显示类型',
//         show:'true代表显示，false不显示，默认true',
//         data:{},
//         class:[]
//     },
//     cancelBtn:{
//         text:'okBtn的文字',
//         type:'按钮显示类型',
//         show:'true代表显示，false不显示，默认true',
//         data:{},
//         className:[]//'a'/['a','b']
//     }
// }
//模态框设置
function setModal(option) {
    let element;
    if (option.element) {
        element = option.element
    } else {
        if (!option.selector) throw Error(`配置文件必须填写selector或者element`)
        element = document.querySelector(option.selector)
        if (!element) throw Error(`没有找到模态框元素`)
    }
    if (option.title != undefined) {
        element.querySelector('.modal-title').innerText = option.title
    }
    if (option.content != undefined) {
        element.querySelector('.modal-body').innerHTML = option.content
    }
    if (option.okBtn) {
        const okBtnEle = element.querySelector('.ok-btn')
        if (option.okBtn.text != undefined) { okBtnEle.innerText = option.okBtn.text }
        if (option.okBtn.show == false) {
            okBtnEle.style.display = 'none'
        } else {
            okBtnEle.style.display = 'inline-block'
        }
        if (option.okBtn.type) {
            let className = okBtnEle.className
            let newClassName = className.replace(/btn-\w+/, `btn-${option.okBtn.type}`)
            okBtnEle.className = newClassName
        }
        if (typeof option.okBtn.data == 'object') {
            const data = option.okBtn.data
            for (key in data) {
                okBtnEle.dataset[key] = data[key]
            }
        }
        if (option.okBtn.className) {
            const className = option.okBtn.className
            if (typeof className == 'string') {
                okBtnEle.classList.add(className)
            } else if (Array.isArray(className)) {
                className.forEach(item => {
                    okBtnEle.classList.add(item)
                })
            }
        }
    }
    if (option.cancleBtn) {
        const cancleBtnEle = element.querySelector('.cancle-btn')
        if (option.cancleBtn.text != undefined) { cancleBtnEle.innerText = option.cancleBtn.text }
        if (option.cancleBtn.show == false) {
            cancleBtnEle.style.display = 'none'
        } else {
            cancleBtnEle.style.display = 'inline-block'
        }
        if (option.cancleBtn.type) {
            let className = cancleBtnEle.className
            let newClassName = className.replace(/btn-\w+/, `btn-${option.cancleBtn.type}`)
            cancleBtnEle.className = newClassName
        }
        if (typeof option.cancleBtn.data == 'object') {
            const data = option.cancleBtn.data
            for (key in data) {
                cancleBtnEle.dataset[key] = data[key]
            }
        }
        if (option.cancleBtn.className) {
            const className = option.cancleBtn.className
            if (typeof className == 'string') {
                cancleBtnEle.classList.add(className)
            } else if (Array.isArray(className)) {
                className.forEach(item => {
                    cancleBtnEle.classList.add(item)
                })
            }
        }
    }
}
/*----------------------弹出提示框封装--------------------------*/
function myAlert(option) {
    option = option || {}
    option.selector = option.selector || "#modal-alert"
    option.title = option.title || '信息提示'
    option.content = option.content ? `<h3>${option.content}</h3>` : ''
    option.okBtn = {
        type: 'success',
        data: {
            dismiss: "modal"
        },
        text: '确定'
    }
    option.cancleBtn = {
        show: false,
    }
    setModal(option)
    $(option.selector).modal('show')

}
// let option = {
//     selector:'模态框选择器',
//     element:'模态框元素',
//     title:'模态框标题',
//     content:'模态框内容',
//     okBtn:{
//         text:'okBtn的文字',
//         type:'按钮显示类型',
//         show:'true代表显示，false不显示，默认true',
//         data:{},
//         class:[]
//     },
//     cancelBtn:{
//         text:'okBtn的文字',
//         type:'按钮显示类型',
//         show:'true代表显示，false不显示，默认true',
//         data:{},
//         className:[]//'a'/['a','b']
//     }
// }
/*
 触发点击事件 -> 请求数据 -> 拿到返回的数据并解析 -> 渲染到网页
*/